import axios from "axios";
import { Review, Product, User } from "@/types";

const apiClient = axios.create({
  baseURL: process.env.NEXT_PUBLIC_API_BASE_URL || "http://localhost:8081/api",
  headers: {
    "Content-Type": "application/json",
  },
  withCredentials: true, // This is the key for automatic cookie handling
});

// Product APIs
export const getProducts = async (): Promise<Product[]> => {
  const response = await apiClient.get<Product[]>("/products");
  return response.data;
};

export const getProductById = async (id: string): Promise<Product> => {
  const response = await apiClient.get<Product>(`/products/${id}`);
  return response.data;
};

// Review APIs
export const getReviews = async (productId: string): Promise<Review[]> => {
  const response = await apiClient.get<Review[]>(`/products/${productId}/reviews`);
  return response.data;
};

export const addReview = async (review: Omit<Review, 'rowKey' | 'reviewDate' | 'userId' | 'userName'>) => {
    const { productId, ...reviewData } = review;
    if (!productId) {
        throw new Error("productId is required to add a review.");
    }
    const response = await apiClient.post(`/products/${productId}/reviews`, reviewData);
    return response.data;
};

// User APIs
export const loginUser = async (user: User) => {
    const response = await apiClient.post('/users/login', user);
    // The browser will handle the cookie automatically.
    // We just return the user data.
    return response.data;
};

export const registerUser = async (user: User) => {
  const response = await apiClient.post("/users/register", user);
  return response.data;
};

// Cart APIs
export const getCart = async () => {
  const response = await apiClient.get("/cart");
  return response.data;
};

export const addToCart = async (productId: string, quantity: number) => {
  const response = await apiClient.post("/cart/items", { productId, quantity });
  return response.data;
};

export const removeFromCart = async (productId: string) => {
  const response = await apiClient.delete(`/cart/items/${productId}`);
  return response.data;
};

export const updateCartItemQuantity = async (productId: string, quantity: number) => {
    const response = await apiClient.put(`/cart/items/${productId}`, { quantity });
    return response.data;
};

export const clearCart = async () => {
    const response = await apiClient.delete('/cart');
  return response.data;
};

// Admin APIs
export const addProduct = async (product: Omit<Product, 'id'>) => {
    const response = await apiClient.post('/admin/products', product);
    return response.data;
};

export const updateProduct = async (productId: string, product: Omit<Product, 'id'>) => {
    const response = await apiClient.put(`/admin/products/${productId}`, product);
    return response.data;
}

export const deleteProduct = async (productId: string) => {
    const response = await apiClient.delete(`/admin/products/${productId}`);
    return response.data;
}

export const uploadImage = async (file: File) => {
    const formData = new FormData();
    formData.append('file', file);
    const response = await apiClient.post('/admin/products/upload-image', formData, {
        headers: {
            'Content-Type': 'multipart/form-data',
        },
    });
    return response.data;
} 